<template>
  <div class="plan-edit-box"
    element-loading-text="数据加载中"
    element-loading-spinner="el-icon-loading"
    v-loading="pageLoading">
    <div class="plan-page-header">
      <div class="header-title">{{title}}</div>
      <processButtons
        v-if="!hiddenBtnGroup"
        :disabledPage="disabledPage"
        :disabledAction="disabledAction"
        :fromPage="fromPage"
        sourceAction="midtermEdit"
        :dataStatus="dataStatus"
        :bindId="modelForm.bindId || ''"
        :writePermission="writePermission"
        :rejectFlag="modelForm.rejectFlag"
        :submitFlag="submitFlag"
        :oldDataFlag="modelForm.oldDataFlag"
        @hide="hideFun"
        @save="save"
        @submit="save"
        @modify="save"
        @withdraw="save"
        @approve="changeStatus"
        @reject="changeStatus"
        @process="goProcessPage"
      >
      </processButtons>
      <div class="header-btns" v-if="hiddenBtnGroup">
        <RPButton optType="reset" style="margin-right: 10px"  @click="hideFun" text="取消" />
      </div>
    </div>
    <!-- <div>33:{{this.modelForm.trgNode}}</div> -->
    <div class="plan-page-content">
      <div :class="(id || modelForm.code1) ? 'disableFontcolor' : ''">
      <Form :model="modelForm" ref="editForm" class="ivu-form-no-margin-bottom" :rules="rule" :label-width="150">
        <Row :gutter="20" class="code-row-bg" v-if="useApiGetData">
          <Col span="24" style="border:none;">
            <Form-item prop="trgNode" label="业务单元："  >
              <Select filterable  v-model="modelForm.trgNode" :disabled="true">
                <Option @click.native="codeChange(item)"  :title="$t('common.valid')" v-for="item in businessUnit" :value="item.trgNode" :key="item.trgNode">{{item.trgNode}}</Option>
              </Select>
            </Form-item>
          </Col>
        </Row>
        <!-- <Row :gutter="20" class="code-row-bg" v-show="!disabledPage && (associationData.length != 1)">
          <Col span="24" style="border:none;">
            <Form-item prop="code1" label="关联表：" v-show="true">
              <span slot="label">
                  {{'关联表：'}}
                  <Tooltip max-width="200" content="ssfa+业务单元缩写+举措大类序号+单据唯一标识" placement="top">
                      <Icon type="ios-help-circle-outline" />
                  </Tooltip>
              </span>
              <Select style="line-height:30px"  v-model="modelForm.code1" filterable
              :loading="code1loading"
              :remote-method="() => {}"
              @on-query-change="getListByValue"
              @on-clear="getListByValue"  clearable>
                <Option :title="$t('common.valid')" v-for="(item, index) in associationTable" :value="item.id" :key="item.taskCode + index">{{item.taskCode}}</Option>
              </Select>
            </Form-item>
          </Col>
        </Row> -->
        <Row :gutter="20" class="code-row-bg">
          <Col span="24" style="border:none;">
            <Form-item prop="stype" label="举措大类：" >
              <Select  v-model="modelForm.stype">
                <Option @click.native="stypeChange(item)" :title="$t('common.valid')" v-for="item in categoryInitiatives" :value="item.vsiValue" :key="item.vsiValue">{{item.vsiValue}}</Option>
              </Select>
            </Form-item>
          </Col>
        </Row>
        <Row :gutter="20" class="code-row-bg">
          <Col span="24" style="border:none;">
            <Form-item prop="mtype" label="举措细类：" >
              <Select  v-model="modelForm.mtype" >
                <Option :title="$t('common.valid')" v-for="item in detailsInitiatives" :value="item.vsiValue" :key="item.vsiValue">{{item.vsiValue}}</Option>
              </Select>
            </Form-item>
          </Col>
        </Row>
        <Row :gutter="20" class="code-row-bg">
          <Col span="24" style="border:none;">
            <Form-item prop="taskdesc" label="关键任务：">
              <RadioGroup v-model="modelForm.taskdesc" >
                <Radio label="是"></Radio>
                <Radio label="否"></Radio>
              </RadioGroup>
            </Form-item>
          </Col>
        </Row>
        <Row :gutter="20" class="code-row-bg">
          <Col span="24" style="border:none;">
            <Form-item prop="highTask" label="重点任务：">
              <Input v-model="modelForm.highTask" :maxlength="1000" type="textarea" :rows="4" placeholder="请输入" />
            </Form-item>
          </Col>
        </Row>

        <Row :gutter="20" class="code-row-bg">
          <Col span="24" style="border:none;">
            <Form-item prop="taskMod" label="落实举措：">
              <Input v-model="modelForm.taskMod" :maxlength="1000" type="textarea" :rows="4" placeholder="请输入" />
            </Form-item>
          </Col>
        </Row>

        <Row :gutter="20" class="code-row-bg">
          <Col span="24" style="border:none;">
            <Form-item prop="taskPreRs" label="预期业务价值：">
              <Input v-model="modelForm.taskPreRs" :maxlength="1000" type="textarea" :rows="4" placeholder="请输入" />
            </Form-item>
          </Col>
        </Row>

        <Row :gutter="20" class="code-row-bg">
          <Col span="24" style="border:none;">
            <Form-item
              :required="timeRequired"
              prop="startDate"
              label="计划开始时间：">
              <DatePicker :editable = false  @on-change="startDateChange" :options="optionss" v-model="modelForm.startDate" type="month" placeholder="请选择计划开始时间" style="width: 200px" />
              <!-- <DatePicker v-model="modelForm.startDate" type="datetime" placeholder="请选择计划开始时间" style="width: 200px" /> -->
              <!-- <DatePicker :model-value="modelForm.startDate" type="date" placeholder="Select date" style="width: 200px" /> -->
            </Form-item>
          </Col>
        </Row>

        <Row :gutter="20" class="code-row-bg">
          <Col span="24" style="border:none;">
            <Form-item
              :required="timeRequired"
              prop="endDate"

              label="计划完成时间：" >
              <DatePicker  :editable = false  @on-change="endDateChange"  :options="optionss" v-model="modelForm.endDate" type="month" placeholder="请选择计划完成时间" style="width: 200px" />
              <!-- <DatePicker v-model="modelForm.endDate" type="datetime" placeholder="请选择计划完成时间" style="width: 200px" /> -->
              <!-- <DatePicker :model-value="modelForm.endDate" type="date" placeholder="Select date" style="width: 200px" /> -->
            </Form-item>
          </Col>
        </Row>
        <Row :gutter="20" class="code-row-bg">
          <Col span="24" style="border:none;">
            <Form-item prop="dpart" label="责任部门：">
              <Input v-model="modelForm.dpart" :maxlength="150" :rows="4" placeholder="请输入" />
            </Form-item>
          </Col>
        </Row>
        <Row :gutter="20" class="code-row-bg">
          <Col span="24" style="border:none;">
            <Form-item prop="progressPercentage" label="进度百分比(%)：">
               <InputNumber class="disableFontcolor" placeholder="请输入" @on-change="percentageChange" :max="100" :min="0" :step="1" :precision="0" v-model="modelForm.progressPercentage" />
            </Form-item>
          </Col>
        </Row>
        <Row :gutter="20" class="code-row-bg">
          <Col span="24" style="border:none;">
          <div class="Selecequarters" >
            <Form-item prop="year" label="季度：">
              <DatePicker :editable = false type="year" v-model="modelForm.year" :options="optionss"  placeholder="请选择年份" style="width: 200px" />
            </Form-item>
            <span style="margin:10px; margin-left: -590px;margin-right:-130px">-</span>
            <Form-item prop="quarter">
              <Select   v-model="modelForm.quarter" style="width: 24%;" placeholder="请选择季度" >
                <Option  v-for="item in datasList"  :key="item.key" :value="item.value">{{item.value}}</Option>
              </Select>
            </Form-item >
          </div>
          </Col>
        </Row>
        <Row :gutter="20" class="code-row-bg">
          <Col span="24" style="border:none;">
            <Form-item prop="currentStatus" label="当前状态：">
              <span slot="label">
                  {{'当前状态：'}}
                  <Tooltip max-width="450" placement="top">
                      <Icon type="ios-help-circle-outline" />
                      <template #content>
                          <p>当前状态判断规则：</p>
                          <p>①若进度百分比为0，且填报季度<计划开始时间，当前状态为 未启动</p>
                          <p>②进度百分比在计划百分比±10%以内，当前状态为 正常进行</p>
                          <p>③进度百分比超前完成10%以上，当前状态为 超额推进</p>
                          <p>④进度百分比延期超过10%以上，当前状态为 延期进行</p>
                          <p>⑤进度百分比为100%，当前状态为 已完成</p>
                      </template>
                  </Tooltip>
              </span>
              <!-- <Select disabled  v-model="modelForm.currentStatus" >
                <Option :title="$t('common.valid')" v-for="item in statusList" :value="item.vsiValue" :key="item.vsiValue">{{item.vsiValue}}</Option>
              </Select> -->
              <!-- <Input v-model="modelForm.currentStatus" type="textarea" :rows="4" placeholder="--" /> -->
              <Input class="disableFontcolor" v-model="modelForm.currentStatus" :maxlength="150" disabled :rows="4" placeholder="--" />
            </Form-item>
          </Col>
        </Row>
        <Row :gutter="20" class="code-row-bg">
          <Col span="24" style="border:none;">
            <Form-item prop="statusNotice">
              <div slot="label">进度说明：</br>（每季度更新）</div>
              <Input v-model="modelForm.statusNotice" :maxlength="4000" type="textarea" :rows="4" placeholder="请输入" />
            </Form-item>
          </Col>
        </Row>
        <Row :gutter="20" class="code-row-bg">
          <Col span="24" style="border:none;">
            <Form-item prop="todo" label=" 备注： ">
              <Input v-model="modelForm.todo" :maxlength="4000" type="textarea" :rows="4" placeholder="请输入" />
            </Form-item>
          </Col>
        </Row>
      </Form>
      <Form :model="modelForm" class="ivu-form-no-margin-bottom" :rules="rule" :label-width="150" :disabled="uploading">
        <Row :gutter="20" class="code-row-bg" >
            <Col span="24" style="border:none;">
              <Form-item prop="attachment" label=" 附件： ">
                <div style="display: flex; flex-direction: column;">
                  <Upload
                    v-if="!(disabledPage && id) && dataStatus != 2"
                    ref="upload"
                    multiple
                    :show-upload-list="false"
                    :before-upload="handleUpload"
                    :on-exceeded-size="handleMaxSize"
                    :on-error="handleError"
                    :on-success="handleSuccess"
                    accept=".xls,.xlsx,.doc,.docx,.pdf,.ppt,.pptx,.jpg,.jpeg,.png,.rar,.zip"
                    :headers="uploadHeaders"
                    :data="uploadData"
                    :action="uploadUrl"
                    :max-size="1024*15">
                    <Button icon="ios-cloud-upload-outline">{{ uploadText }}</Button>
                  </Upload>
                  <span>支持上传 xls .xlsx .doc .docx .pdf .ppt .pptx .jpg .jpeg .png .rar .zip 格式文件</span>
                  <div v-for="(item, index) in uploadList" :key="index" style="display: flex; flex-direction:row;">
                    <div style="width: 90%;">
                      <Icon type="ios-attach" />
                      {{ item.name }}
                    </div>
                    <div style="width: 10%; display: flex; flex-direction: row-reverse;">
                      <Button type="text" size="large" icon="ios-trash-outline" style="margin: 0;width: 30px;height: 30px;" @click="deleteFile(item,true)"></Button>
                    </div>
                  </div>
                  <div v-for="item in modelForm.files" :key="item.id" style="display: flex; flex-direction:row;">
                    <div style="width: 90%;">
                      <Icon type="ios-attach" />
                      {{ item.fileName }}.{{ item.fileType }}
                    </div>
                    <div style="width: 10%; display: flex; flex-direction: row-reverse;">
                      <Button type="text" size="large" icon="ios-trash-outline" style="margin: 0;width: 30px;height: 30px;" @click="deleteFile(item,false)"></Button>
                      <Button type="text" size="large" icon="ios-download-outline" style="margin: 0;width: 30px;height: 30px;" @click="downloadFile(item)"></Button>
                    </div>
                  </div>
                </div>
              </Form-item>
            </Col>
        </Row>
      </Form>
      </div>
    </div>
  </div>

</template>
<script>
import coverApi from '../../api/cover'
import sysConfigApi from '@/api/sysConfig.js'
import todoApi from '../../api/todoCender'
import { planStatus, categoryInitiatives } from '@/api/planDataConfig.js'
import processButtons from '@/components/processButtons'
import approvalOpinion from '@/components/ListView/approvalOpinion'
import diffrentQuarterConfirm from './diffrentQuarterConfirm'
import permission from '@/mixin/permission'
import { PROCESS_STATUS_WAIT_APPROVE, PROCESS_STATUS_APPROVED, PROCESS_STATUS_WAIT_SUBMIT } from '@/tools/common.js'
export default {
  components: {
    processButtons
  },
  name :'midtermEdit',
  mixins: [ permission ],
  props: {
    id: {
      type: String,
      default() {
        return "";
      }
    },

    disabledPage: {
      type: Boolean,
      default: false
    },
    hiddenBtnGroup: {
      type: Boolean,
      default: false
    },
    code: {
      type: String,
      default: '',
    },
    fromPage: {
      type: String,
      default: 'creater',
    },
    dataStatus: {
      type: Number,
      default: 0,
    },
    tableId: {
      type: String,
      default: '',
    },
    associationData: {
      type: Array,
      default: () => []
    },
    writePermission: {
      type: Boolean,
      default: true
    },
    submitFlag: {
      type: String,
      default: ''
    },
    fromAction: {
      type: String,
      default: ''
    },
  },
  data() {
    const Ckeckyear =  (rule, value, callback) => {
      if (!value) {
          callback(new Error('请选择年份'))
        }else {
          callback()
        }
    }
    const checkProgressPercentage = (rule, value, callback) => {
      if (value === null || value === '') {
        callback(new Error('请输入进度百分比'))
      } else {
        callback()
      }
    }

    return {
      uploading: false,
      uploadText: '上传文件',
      uploadErrorMessage: [],
      uploadBatchList: [],
      uploadBatchFinishList: [],
      uploadList: [] ,
      uploadData: {"bizId":'0'},
      uploadHeaders: {'authorization': localStorage.Authorization ? `Bearer ${localStorage.Authorization}` : ''},
      uploadUrl: coverApi.getPlantaskUploadUrl(),
      useApiGetData: true,
      code1loading: false,
      title: '',
      //关联表
      associationTable: [],
      //业务单元
      businessUnit: [],
      //  举措大类
      categoryInitiatives: [],
      //  举措细类
      detailsInitiatives: [],
      // 当前状态
      statusList: planStatus,
      vsiDescription: '',
      pageLoading: false,
      selectValue: null,
      timeRequired: false,
      disabledAction: false,
      modelForm: {
        code1: '',
        trgNode: this.code,
        stype: '',
        mtype: '',
        taskdesc: '',
        // highTaskNo:'',
        highTask: '',
        taskMod: '',
        taskPreRs: '',
        currentStatus: '',
        startDate: '',
        taskQuarter:'',
        endDate: '',
        dpart: '',
        statusNotice: '',
        todo: '',
        year:'',
        quarter:'',
        wfTitle:'',
        progressPercentage: null,
        // 是否关联数据 00--否， 01--是
        relevanceDataFlag: '',
        files:[],
        fileIds:[]
      },
      modelFormDisabled: false,
      rule: {
        trgNode: [{ required: true, message: "请选择业务单元", trigger: "change" }],
        year:[{ required: true,validator: Ckeckyear, message: "请选择年份", trigger: "change" }],
        quarter:[{ required: true, message: "请选择季度", trigger: "change" }],
        progressPercentage:[{ required: true, validator: checkProgressPercentage.bind(this), trigger: "blur" }]
      },
      datasList:[
          {key:'0',value:'1'},
          {key:'1',value:'2'},
          {key:'2',value:'3'},
          {key:'3',value:'4'},
      ],
     optionss:{
      disabledDate(date){
        const disabledDate = date.getFullYear()
        return ( disabledDate > 2025 || disabledDate < 2021 )
      }
     },

    };
  },
  created() {
    // 获取下拉 数据
    this.title = '《数字化转型专项实施方案任务表》中期修改'
  },
  watch: {
    'modelForm.code1': {
      handler(val) {
        if (val) {
             coverApi.getCoverDetail({
              type: this.fromPage,
              data: {id: val}
             }).then(res => {
                let data = res.data.data.taskQuarter? res.data.data.taskQuarter.split('-',2):''
                let info = {
                      trgNode:  res.data.data.trgNode,
                      stype: res.data.data.stype,
                      mtype: res.data.data.mtype,
                      taskdesc: res.data.data.taskdesc,
                      // highTaskNo: res.data.data.highTaskNo,
                      highTask: res.data.data.highTask,
                      taskMod: res.data.data.taskMod,
                      taskPreRs: res.data.data.taskPreRs,
                      currentStatus: res.data.data.currentStatus,
                      startDate: res.data.data.startDate,
                      taskQuarter:res.data.data.taskQuarter,
                      endDate: res.data.data.endDate,
                      dpart: res.data.data.dpart,
                      statusNotice: res.data.data.statusNotice,
                      todo: res.data.data.todo,
                      progressPercentage: res.data.data.progressPercentage || null,
                      year: res.data.data.taskQuarter? new Date(res.data.data.taskQuarter).Format('yyyy'):'',
                      quarter:data[1],
                }

                this.modelForm = {
                  ...this.modelForm,
                  ...info
                }
                this.detailsInitiatives = this.categoryInitiatives.find(item => item.vsiValue == this.modelForm.stype) ?
                this.categoryInitiatives.find(item => item.vsiValue == this.modelForm.stype).children : []

                this.pageLoading = false
              })
              this.modelForm.relevanceDataFlag = '01'
          } else {
            this.modelForm.relevanceDataFlag = '00'
          }
        }
      },
      'modelForm.relevanceDataFlag': {
        handler(val) {
          if(val == '01') {
            this.modelFormDisabled = true
          } else if(val == '00') {
            this.modelFormDisabled = false
          }
        }
      },
      'modelForm.progressPercentage': {
        handler(val) {
          if(val == null) {
            this.modelForm.currentStatus = ''
          }
        }
      }
    },
  beforeMount: function() {},
  mounted() {
    this.categoryInitiatives = categoryInitiatives
    coverApi.getRptReportTrgnodePList({reportName: "数字化转型专项实施方案任务表"}).then(res => {
      this.businessUnit = res.data.data
      this.$nextTick(() => {
        this.init()
      })
    })
    this.uploadList = this.$refs.upload ? this.$refs.upload.fileList : [];
  },
  beforeDestroy: function() {},
  destroyed: function() {},
  methods: {
      deleteFile(file,local) {
        let _this = this
        this.$confirm({
                      title:"删除",
                      content: "确认删除?"
                    }).then(()=>{
                      if (local) {
                        _this.uploadList = _this.uploadList.filter(item => item.fileId !== file.fileId)
                      }else {
                        _this.modelForm.files = _this.modelForm.files.filter(item => item.id !== file.id)
                      }
                    })
      },
      downloadFile(file) {
        coverApi.plantaskDownloadFile(file.id)
      },
      checkBacthUploadFinishAndShowMessage(){
        if(this.uploadBatchList.length <= this.uploadBatchFinishList.length){
          this.uploadBatchList = []
          this.uploadBatchFinishList = []
          this.uploading = false
          this.uploadText = '上传文件'
          this.$Message.success('文件上传成功')
          // this.$Spin.hide();
          if(this.uploadErrorMessage.length > 0){
            // this.$Message.error(this.uploadErrorMessage.join(','))
            this.uploadErrorMessage = []
          }
        }

      },
      handleSuccess(res, file) {
        this.$refs.upload.fileList.forEach(item => {if(item == file){
          item.fileId = res.data
        }})
        this.uploadBatchFinishList.push(file)
        this.checkBacthUploadFinishAndShowMessage()
      },
      handleError(error, res, fileList) {
        this.uploadBatchFinishList.push(file)
        this.uploadErrorMessage.push(res.message)
        this.checkBacthUploadFinishAndShowMessage()
        this.$Message.error(res.message)
      },
      handleMaxSize(file) {
        this.$Message.error('单个文件上传大小不超过15M,请重试')
      },
      handleUpload(file) {
        let totalSize = file.size
        if(totalSize > 15 * 1024 *1024){
          this.$Message.error('单个文件上传大小不超过15M,请重试')
          return false
        }
          this.$refs.upload.fileList.forEach(item => totalSize = totalSize + item.size)
          if (this.modelForm.files instanceof Array) {
            this.modelForm.files.forEach(item => totalSize = totalSize + item.fileSize)
          }
          if (totalSize > 100 * 1024 *1024) {
            this.$Message.error('总文件上传大小不超过100M,请重试')
            // this.uploadErrorMessage.push('总文件上传大小不超过100M,请重试')
            return false
          } else {
            this.uploadBatchList.push(file)
            this.uploading = true
            this.uploadText = '文件上传中...'
            return true
          }
      },
      changeStatus() {
      new this.$pageModal(
        approvalOpinion,
        {
          props: {
          }
        },
        async (data) => {
          if (!data) return
          todoApi.changeRowStatus({
            id: this.modelForm.id,
            tableId: this.tableId,
            approverComments: data.approverComments
          }, data.result == '通过' ? true : false).then(() => {
            this.$Message.success({
              content: '操作成功',
              duration: 3
            })
            this.$nextTick(() => {
              this.$emit('Close', true)
            })
          }).finally(() => {
            this.disabledAction = false
          })
        }
      )
    },
     getListByValue(value) {
          if(value == undefined || value == '') {
            this.modelFormDisabled = false
          } else {
            this.modelFormDisabled = true
          }
          if (this.associationTable.find(item => item.taskCode == value)) {
            return false
          }
          this.selectValue = value
          this.getListData()
    },
    codeChange() {
      this.$nextTick(() => {
        this.getListData()
      })
    },

     getListData() {
      if (this.associationData.length == 1) {
        this.associationTable = this.associationData
        this.$set(this.modelForm, 'trgNode', this.associationData[0].trgNode)
        this.$set(this.modelForm, 'code1', this.associationData[0].id)
        return
      }
      this.code1loading = true

      let params = {
           taskCode: this.selectValue,
           trgNode: this.modelForm.trgNode || this.code,
           stype: '',
           mtype: '',
           currentPage:  1,//当前页码
           pageSize: 100, //每页条数
           sortOrderBy: 'DESC',
           sortPropName: 'create_time'
      }
       coverApi.getCoverTableList({
        data: params,
        type: this.fromPage
       }).then(res => {
            let { records } = res.data.data
            if (!records || !records.length || !records.find(item => item.id == this.modelForm.code1)) {
              this.modelForm.code1 = null
              this.selectValue = null
            }
            this.associationTable = records || []
            this.code1loading = false
          })
    },
    endDateChange(val) {
      if (val && this.modelForm.startDate && new Date(this.modelForm.startDate).Format('yyyy-MM') > val ) {
        this.$Message.error({
          content: '计划完成时间不能早于计划开始时间',
          duration: 3
        });
        this.modelForm.endDate = ''
      } else {
          this.$refs["editForm"].validateField('endDate')
          if(this.modelForm.endDate == null) {
            this.modelForm.endDate = new Date(val)
          }
      }
      if(this.modelForm.startDate == '' || this.modelForm.endDate == ''){
        this.modelForm.currentStatus = ''
      } else {
        if(this.modelForm.progressPercentage !== null) {
          this.percentageChange()
        }
      }
    },
    startDateChange(val) {
      if (val && this.modelForm.endDate && new Date(this.modelForm.endDate).Format('yyyy-MM') < val ) {
        this.$Message.error({
          content: '计划完成时间不能早于计划开始时间',
          duration: 3
        });
        this.modelForm.startDate = ''
      } else {
         this.$refs["editForm"].validateField('startDate')
        if(this.modelForm.startDate == null) {
          this.modelForm.startDate = new Date(val)
        }
      }
      if(this.modelForm.startDate == '' || this.modelForm.endDate == ''){
        this.modelForm.currentStatus = ''
      } else {
        if(this.modelForm.progressPercentage !== null) {
          this.percentageChange()
        }
      }
    },
    stypeChange(list) {
      this.detailsInitiatives = list.children
      this.modelForm.mtype = ''
    },
    hideFun() {
      this.$parent.hide()
    },
    //获取详情
     init() {
      if (this.id) {
        coverApi.getCoverDetail({
          type: this.fromPage,
          data: {id: this.id}
        }).then(res => {
            let getInfoData = {...res.data.data}
            delete getInfoData.currentStatus
            this.modelForm = {
              ...this.modelForm,
              code:this.code,
              ...getInfoData,
            }
            this.modelForm.year = this.modelForm.taskQuarter? new Date(this.modelForm.taskQuarter).Format('yyyy'):''
            let data = this.modelForm.taskQuarter? this.modelForm.taskQuarter.split('-',2):''
            this.modelForm.quarter = data[1]
            this.detailsInitiatives = this.categoryInitiatives.find(item => item.vsiValue == this.modelForm.stype) ?
            this.categoryInitiatives.find(item => item.vsiValue == this.modelForm.stype).children : []
            let progressPercentage = res.data.data.progressPercentage
            this.$nextTick(() => {
              if (progressPercentage === null || progressPercentage === 0 || progressPercentage === undefined) {
                this.modelForm.currentStatus = '--'
              } else {
                let currentStatus = res.data.data.currentStatus
                this.modelForm.currentStatus = currentStatus ? currentStatus : '--'
              }
            })
            this.pageLoading = false
            this.modelForm.startDate = getInfoData.startDate ? getInfoData.startDate : ''
            this.modelForm.endDate = getInfoData.endDate ? getInfoData.endDate : ''
            this.modelForm.progressPercentage = (progressPercentage === null || progressPercentage === 0 || progressPercentage === undefined) ? null : Number(getInfoData.progressPercentage)
            if (this.disabledPage && this.fromPage == 'Approver') {
              this.businessUnit = [{
                "trgNode": this.modelForm.trgNode
              }]
            }
          })
      } else {
        this.pageLoading = false
        this.getListData()
      }
    },

    Update(params, content){
      this.disabledAction = true
      params = this.setCurrentStatus(params)
      coverApi.coverAdminUpdate({
        type: this.fromPage,
        data: params
      }).then(res => {
        if(res.data.code == 200) {
          this.$Message.success({
            content: content,
            duration: 3
          });
          this.$emit('Close', true)
        } else {
          this.$Message.error({
            content: res.data.msg || '操作失败',
            duration: 3
          });
        }
      }).finally(() => {
        this.disabledAction = false
      })
    },
    save() {
      //let self = this
      if(this.uploading){
        this.$Message.error({
            content: '文件上传中，请稍后',
            duration: 3
          })
        return
      }
      this.$refs["editForm"].validate(valid => {
        if (valid) {
          if (this.id) {
           //编辑
            let param ={
                ...this.modelForm,
              startDate: this.modelForm.startDate && new Date(this.modelForm.startDate).Format("yyyy-MM-dd hh:mm:ss"),
              endDate: this.modelForm.endDate && new Date(this.modelForm.endDate).Format("yyyy-MM-dd hh:mm:ss")
            }
            if (this.modelForm.year && this.modelForm.quarter) {
              param.taskQuarter = new Date(this.modelForm.year).Format('yyyy') + '-' + this.modelForm.quarter
            } else if (this.modelForm.year && !this.modelForm.quarter) {
              param.taskQuarter = new Date(this.modelForm.year).Format('yyyy') + '-' + 1
            } else if (!this.modelForm.year && this.modelForm.quarter) {
              param.taskQuarter = 2023 + '-' + this.modelForm.quarter
            } else {
              param.taskQuarter = '2023-1'
            }
            delete param.code1
            delete param.updateBy
            delete param.updateTime
            if(!param.fileIds){
              param.fileIds = []
            }
            if(param.files){
              param.files.forEach(item => param.fileIds.push(item.id))
            }
            this.uploadList.forEach(item => param.fileIds.push(item.fileId))
            this.Update(param, '中期修改成功')
          }
        } else {
          this.$Message.error({
            content: '请完善表单信息',
            duration: 3
          });
          return 0;
        }
      });
    },
    diffrentQuarterConfirm(data, configQuarter) {
      new this.$pageModal(
        diffrentQuarterConfirm,
        {
          props: {
            fromAction: 'updateProgress',
            data,
            configQuarter
          }
        },
        (data) => {
          if (data) {
            let actionSource = data.actionSource
            let msg = ''
            if (actionSource == 'NotModifyAndSubmit') {
              if (data.wfStatus == PROCESS_STATUS_WAIT_APPROVE) {
                msg = '保持并提交成功'
              } else if (data.wfStatus == PROCESS_STATUS_WAIT_SUBMIT) {
                msg = '保存成功'
              }
            } else if (actionSource == 'ModifyAndSubmit') {
              data.taskQuarter = configQuarter
              data.year = data.taskQuarter? new Date(data.taskQuarter).Format('yyyy'):''
              data.quarter = data.taskQuarter.split('-')[1] ? data.taskQuarter.split('-')[1] : ''
              if (data.wfStatus == PROCESS_STATUS_WAIT_APPROVE) {
                msg = '修改季度并提交成功'
              } else if (data.wfStatus == PROCESS_STATUS_WAIT_SUBMIT) {
                msg = '修改季度并保存成功'
              }
            }
            this.Update(data, msg)
          }
        }
      );
    },
    _getMonthDiff(date1, date2) {
      let months;
      months = (date2.getFullYear() - date1.getFullYear()) * 12;
      months -= date1.getMonth() + 1;
      months += date2.getMonth() + 1;
      return months;
    },
    setCurrentStatus(data) {
      let params = JSON.parse(JSON.stringify(data))
      const progressPercentage = params.progressPercentage / 100
      if(progressPercentage == 1){
        params.currentStatus = '已完成'
        return params
      }
      const startDate = new Date(params.startDate)
      const endDate = new Date(params.endDate)
      const year = params.year
      const quarter = params.quarter
      
      if((params.startDate == '' || params.startDate == null)
        || (params.endDate == '' || params.endDate == null)
        || (year == '' || year == null)
        || (quarter == '' || quarter == null)){
        params.currentStatus = ''
      } else {
        // x当前日期距离计划开始时间的长度。当前时间在计划开始时间之前，结果为负值；当前时间在计划开始时间之后，结果为正值
        // 按照需求要求，设想开始日期为选中季度的最后一个月
        const quarterMap = {"1": '03', "2": "06", "3": "09", "4": "12"}
        const fakeStartDate = new Date(new Date(year).Format('yyyy') + '-' + quarterMap[quarter] + '-01: 00:00:00')
        if (fakeStartDate.getTime() > endDate.getTime()) {
          params.currentStatus = '延期进行'
          return params
        }
        const x = this._getMonthDiff(startDate, fakeStartDate) + 1
        // y 计划完成时间距离计划开始时间的长度
        const y = this._getMonthDiff(startDate, endDate) + 1
        const z = x / y
        if(progressPercentage <= 0 && z <= 0) {
          params.currentStatus = '未启动'
        } else if(progressPercentage > 0 && z > 0 && (progressPercentage >= (z - 0.1).toFixed(2) && progressPercentage <= (z + 0.1).toFixed(2))){
          params.currentStatus = '正常进行'
        } else if(progressPercentage > 0 && z > 0 && (progressPercentage > (z + 0.1).toFixed(2))){
          params.currentStatus = '超额推进'
        } else if(progressPercentage > 0 && z > 0 && (progressPercentage < (z - 0.1).toFixed(2))){
          params.currentStatus = '延期进行'
        } else if(progressPercentage > 0 && z <= 0){
          params.currentStatus = '超额推进'
        } else if(progressPercentage <= 0 && z > 0) {
          params.currentStatus = '延期进行'
        }
      }
      return params
    },
    percentageChange() {
      const progressPercentage = this.modelForm.progressPercentage / 100
      if(progressPercentage == 1){
        this.modelForm.currentStatus = '已完成'
        return
      }
      const startDate = this.modelForm.startDate
      const endDate = this.modelForm.endDate
      const year = this.modelForm.year
      const quarter = this.modelForm.quarter
      
      if((startDate == '' || startDate == null)
        || (endDate == '' || endDate == null)
        || (year == '' || year == null)
        || (quarter == '' || quarter == null)){
        this.modelForm.currentStatus = ''
      } else {
        // x当前日期距离计划开始时间的长度。当前时间在计划开始时间之前，结果为负值；当前时间在计划开始时间之后，结果为正值
        // 按照需求要求，设想开始日期为选中季度的最后一个月
        const quarterMap = {"1": '03', "2": "06", "3": "09", "4": "12"}
        const fakeStartDate = new Date(new Date(year).Format('yyyy') + '-' + quarterMap[quarter] + '-01: 00:00:00')
        if (fakeStartDate.getTime() > this.modelForm.endDate.getTime()) {
          this.modelForm.currentStatus = '延期进行'
          return 
        }
        const x = this._getMonthDiff(this.modelForm.startDate, fakeStartDate) + 1
        // y 计划完成时间距离计划开始时间的长度
        const y = this._getMonthDiff(startDate, endDate) + 1
        const z = x / y
        if(progressPercentage <= 0 && z <= 0) {
          this.modelForm.currentStatus = '未启动'
        } else if(progressPercentage > 0 && z > 0 && (progressPercentage >= (z - 0.1).toFixed(2) && progressPercentage <= (z + 0.1).toFixed(2))){
          this.modelForm.currentStatus = '正常进行'
        } else if(progressPercentage > 0 && z > 0 && (progressPercentage > (z + 0.1).toFixed(2))){
          this.modelForm.currentStatus = '超额推进'
        } else if(progressPercentage > 0 && z > 0 && (progressPercentage < (z - 0.1).toFixed(2))){
          this.modelForm.currentStatus = '延期进行'
        } else if(progressPercentage > 0 && z <= 0){
          this.modelForm.currentStatus = '超额推进'
        } else if(progressPercentage <= 0 && z > 0) {
          this.modelForm.currentStatus = '延期进行'
        }
      }
    },
    goProcessPage() {
     coverApi.getProcessUrl({ id: this.modelForm.bindId, deviceType: 'PC' }).then(res => {
        window.open(res.data.data)
      })
    }
  },
  directives: {},
};
</script>

<style lang="less" scoped>
/deep/.ivu-btn-warning {
    padding: 4px 23px;
    border-color: #ff6f4b;
    border-radius: 0;
    background-color: #ff6f4b;
}
.plan-edit-box {
  display: flex;
  overflow: hidden;
  flex-direction: column;
  height: 100%;
  .plan-page-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 20px;
    height: 60px;
    .header-title {
      font-weight: bold;
      font-size: 16px;
    }
  }
  .plan-page-content {
    overflow-x: hidden;
    overflow-y: scroll;
    flex: 1;
    padding: 0 20%;
  }
}

/deep/.ivu-btn-large{
    margin-right: 10px;
}




.Selecequarters{
  display:flex;
  /deep/.ivu-form-item-content{
      margin-left: -446px;
  }
  /* /deep/.ivu-form-item-require{
    margin-left:-152px;
  } */

  /deep/.ivu-form-item-content{
        margin-left: 2px;
        width: 800px;

  }
}

/* /deep/.ivu-form-item-content{
    margin-left: 10px;
    width: 800px;
} */
/deep/.ivu-select-small .ivu-select-input, .ivu-select-small.ivu-select-multiple .ivu-select-input {
    top: 0px;
  height: 32px;
    line-height: 32px;
}
.disableFontcolor {
  /deep/.ivu-select-selected-value, 
  /deep/.ivu-input-disabled, 
  // /deep/.ivu-input-number-input,
  /deep/.ivu-input-number-input[disabled],
  /deep/.ivu-select-placeholder,
  /deep/.ivu-select-input
  {
    -webkit-text-fill-color: #666666;
  }
}
/deep/.ivu-input-number-disabled .ivu-input-number-input {
  opacity: 1;
}
</style>
